package com.example.ccj.b.c.custom.adapter;


import android.content.res.Resources;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.file.FileAdapterDeleteListener;
import com.example.ccj.b.c.custom.file.FileMode;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.FileUtils;
import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.media.MediaUtils;
import com.example.ccj.u.update.DownloadUtil;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 文件列表
 */
public class AdapterExportFileList extends RecyclerView.Adapter<AdapterExportFileList.ViewHolder>{
    private final List<FileMode> fileList;
    private int oldId = -1;
    private FileAdapterDeleteListener listener;
    private boolean isCanModify;


    public AdapterExportFileList(@NonNull List<FileMode> fileList, boolean isCanModify, FileAdapterDeleteListener listener){
        this.fileList = fileList;
        this.listener = listener;
        this.isCanModify = isCanModify;

    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.
                from(parent.getContext()).
                inflate(R.layout.adapter_all_export_files, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        FileMode fileMode = fileList.get(position);

        if (StringUtils.endsWithEquals(fileMode.path,"jpg","jpeg","png","gif")) {
            ImageUtils.loadImage(holder.fileImg.getContext(),fileMode.path,holder.fileImg);
        } else {
            int fileImage = getFileImage(fileMode.path);
            holder.fileImg.setImageResource(fileImage);
        }

        holder.fileName.setText(FileUtils.getUrlPathFileName(fileMode.path));
        holder.itemView.setOnClickListener(setItemViewClickListener(fileMode));
        if (isCanModify) {
            holder.delete.setVisibility(View.VISIBLE);
            holder.delete.setOnClickListener(delete(fileMode,position));
        } else {
            holder.delete.setVisibility(View.GONE);
        }
    }

    private View.OnClickListener delete( FileMode file,int position){
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) listener.onDelete(file,position);
            }
        };
    }

    private View.OnClickListener setItemViewClickListener(FileMode fileMode) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用系统打开文件
                if (fileMode.type == FileMode.LOCAL_FILE && fileMode.file == null) {
                    FileUtils.openFile(v.getContext(),fileMode.path);
                } else if (fileMode.type == FileMode.NETWORK_FILE) {
                    int fileType = getFileType(fileMode.path);
                    //图片文件使用大图加载
                    if (fileType == PICTURE_RADIO) {
                        LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(fileMode.path);
                        ArrayList<LocalMedia> list = new ArrayList<>();
                        list.add(localMedia);
                        MediaUtils mediaUtils = new MediaUtils();
                        mediaUtils.openPreview(v.getContext(),0,false,list);
                    } else {
                        //其他文件先判断是否存在在下载
                        String dirPath =  v.getContext().getExternalFilesDir(null) + "/download";
                        String s = dirPath + DownloadUtil.getNameFromUrl(fileMode.path);
                        //判断文件是否存在
                        if (!FileUtils.isFileExists(s)) {
                            FileUtils.openFile(v.getContext(),s);
                            fileMode.file = new File(s);
                            return;
                        }

                        LoadingDialog loadingDialog = new LoadingDialog(v.getContext());
                        loadingDialog.showUpload(100);

                        //其他文件先下载再调用系统加载
                        DownloadUtil.get().downloadUrlFile(fileMode.path, dirPath, new DownloadUtil.OnDownloadListener() {
                            @Override
                            public void onDownloadSuccess(String filePath) {
                                //更新本地文件
                                fileMode.file = new File(filePath);
                                //下载完毕调用系统功能打开
                                FileUtils.openFile(v.getContext(),filePath);
                            }

                            @Override
                            public void onDownloading(int progress) {
                                loadingDialog.setSpeed(progress);
                            }

                            @Override
                            public void onDownloadFailed(String error) {
                                loadingDialog.dismiss();
                                new ErrorDialog(v.getContext(),error);
                            }
                        });
                    }

                }
            }
        };
    }

    @Override
    public int getItemCount() {
        return fileList.size();
    }


    static class ViewHolder extends  RecyclerView.ViewHolder{
        private final ImageView fileImg,delete;
        private final TextView fileName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            fileImg = itemView.findViewById(R.id.adapter_all_export_file_img);
            fileName = itemView.findViewById(R.id.adapter_all_export_file_text);
            delete = itemView.findViewById(R.id.adapter_all_export_file_delete);

            /*
             * 设置水波纹背景
             */
            if (itemView.getBackground() == null) {
                TypedValue typedValue = new TypedValue();
                Resources.Theme theme = itemView.getContext().getTheme();
                int top = itemView.getPaddingTop();
                int bottom = itemView.getPaddingBottom();
                int left = itemView.getPaddingLeft();
                int right = itemView.getPaddingRight();
                if (theme.resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true)) {
                    itemView.setBackgroundResource(typedValue.resourceId);
                }
                itemView.setPadding(left, top, right, bottom);
            }
        }
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        //动画
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setAddDuration(500);
        defaultItemAnimator.setRemoveDuration(300);
        defaultItemAnimator.setChangeDuration(200);
        defaultItemAnimator.setMoveDuration(200);
        defaultItemAnimator.setSupportsChangeAnimations(true);
        recyclerView.setItemAnimator(defaultItemAnimator);

        //为RecycleView绑定触摸事件
        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                //首先回调的方法 返回int表示是否监听该方向
                int dragFlags = ItemTouchHelper.UP|ItemTouchHelper.DOWN;//拖拽
                int swipeFlags = ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;//侧滑删除
                return makeMovementFlags(dragFlags,swipeFlags);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                Collections.swap(fileList,viewHolder.getAdapterPosition(),target.getAdapterPosition());
                notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                //侧滑事件
                File file = fileList.get(viewHolder.getAdapterPosition()).file;
                //当前记录的上一个点击位置是删除的位置或者删除位置一下重置值为-1
                if (oldId >= viewHolder.getAdapterPosition()) {
                    notifyItemChanged(oldId);
                    oldId = -1;
                }
                boolean delete = file.delete();
                fileList.remove(viewHolder.getAdapterPosition());
                notifyItemRemoved(viewHolder.getAdapterPosition());
            }

            @Override
            public boolean isLongPressDragEnabled() {
                //是否可拖拽
                return true;
            }
        });
        helper.attachToRecyclerView(recyclerView);
    }

    public void notifyAdd(FileMode file){
        fileList.add(file);
        ActivityUtils.getTopActivity().runOnUiThread(() -> notifyItemInserted(fileList.size() - 1));
    }

    public void notifyRemove(FileMode file){
        int position = fileList.indexOf(file);
        fileList.remove(position);
        ActivityUtils.getTopActivity().runOnUiThread(() -> {
            notifyItemRemoved(position);
            //重新加载从删除位置往下的所有item，如果删除的是中间，自删除的位置到最后开始是做重新添加操作
            //避免下表越界等错误
            notifyItemRangeRemoved(position,getItemCount());
        });
    }

    private void notifyModify(int position){
        ActivityUtils.getTopActivity().runOnUiThread(() -> {
            this.notifyItemChanged(position);
        });
    }


    /**
     * 根据文件类型返回文件图标
     * @param name 文件名
     * @return 文件图标的资源文件
     */
    private int getFileImage(@NonNull String name){
        if (StringUtils.endsWithEquals(name,"xls","xlsx")) return R.mipmap.file_type_excel;
        if (name.endsWith("gif")) return R.mipmap.file_type_gif;
        if (StringUtils.endsWithEquals(name,"html","htm","apk","xml")) return R.mipmap.file_type_html;
        if (StringUtils.endsWithEquals(name,"jpg","jpeg","png")) return R.mipmap.file_type_image;
        if (name.endsWith("mp3")) return R.mipmap.file_type_music;
        if (StringUtils.endsWithEquals(name,"avi","3gp","mp4","m3u","m4a","m4b","m4p","m4u","m4v","mov","mpeg","mpg4","rmvb","wav","wmv")) return R.mipmap.file_type_;
        if (StringUtils.endsWithEquals(name,"ppt","pptx")) return R.mipmap.file_type_ppt;
        if (StringUtils.endsWithEquals(name,"doc","docx")) return R.mipmap.file_type_word;
        if (name.endsWith("wps")) return R.mipmap.file_type_wps;
        if (StringUtils.endsWithEquals(name,"zip","rar")) return R.mipmap.file_type_zip;
        if (name.endsWith("pdf")) return R.mipmap.file_type_pdf;
        if (StringUtils.endsWithEquals(name,"log","txt")) return R.mipmap.file_type_text;
        return R.mipmap.file_type_file;
    }


    public static final int PICTURE_RADIO = 0;
    public static final int SYSTEM = 1;


    /**
     * 根据文件类型返回文件图标
     * @param name 文件名
     * @return 文件图标的资源文件
     */
    private int getFileType(@NonNull String name){

        if (StringUtils.endsWithEquals(name,"xls","xlsx")) return SYSTEM;
        if (name.endsWith("gif")) return PICTURE_RADIO;
        if (StringUtils.endsWithEquals(name,"html","htm","apk","xml")) return SYSTEM;
        if (StringUtils.endsWithEquals(name,"jpg","jpeg","png")) return PICTURE_RADIO;
        if (name.endsWith("mp3")) return SYSTEM;
        if (StringUtils.endsWithEquals(name,"avi","3gp","mp4","m3u","m4a","m4b","m4p","m4u","m4v","mov","mpeg","mpg4","rmvb","wav","wmv")) return PICTURE_RADIO;
        if (StringUtils.endsWithEquals(name,"ppt","pptx")) return SYSTEM;
        if (StringUtils.endsWithEquals(name,"doc","docx")) return SYSTEM;
        if (name.endsWith("wps")) return SYSTEM;
        if (StringUtils.endsWithEquals(name,"zip","rar")) return SYSTEM;
        if (name.endsWith("pdf")) return SYSTEM;
        if (StringUtils.endsWithEquals(name,"log","txt")) return SYSTEM;
        return R.mipmap.file_type_file;
    }


}



